package com.ukao.steward.ui.valetRunners.createOrder;


import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.sunmi.payservice.hardware.aidl.AidlConstants;
import com.sunmi.payservice.hardware.aidl.HardwareOpt;
import com.sunmi.payservice.hardware.aidl.ReadCardCallback;
import com.sunmi.payservice.hardware.aidl.bean.PayCardInfo;
import com.ukao.steward.R;
import com.ukao.steward.base.BaseApplication;
import com.ukao.steward.base.BaseFragment;
import com.ukao.steward.bean.SearchUserBean;
import com.ukao.steward.bean.UserInfoCard;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.eventbus.ReadCardEvent;
import com.ukao.steward.listener.MyTextWatcher;
import com.ukao.steward.retrofit.ApiCallback;
import com.ukao.steward.ui.valetRunners.bingCard.ClientFragment;
import com.ukao.steward.ui.valetRunners.bingCard.SearchUserFragment;
import com.ukao.steward.ui.valetRunners.storeCreatOrder.StoreClientInfoFragment;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.KeyBoardUtil;
import com.ukao.steward.util.L;
import com.ukao.steward.util.StringByteUtils;
import com.ukao.steward.util.T;
import com.ukao.steward.widget.ClearEditText;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.Unbinder;
import info.hoang8f.android.segmented.SegmentedGroup;

import static com.ukao.steward.R.id.confirm_btn;

/**
 * 搜索客户
 */
public class SeachGuestFragment extends BaseFragment {

    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(confirm_btn)
    Button searchBtn;
    @BindView(R.id.edit_text)
    ClearEditText editText;
    @BindView(R.id.tab_one)
    RadioButton tabOne;
    @BindView(R.id.tab_two)
    RadioButton tabTwo;
    @BindView(R.id.segmented_group)
    SegmentedGroup segmentedGroup;


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Unbinder unbinder;
    private String rfidSecret;
    private boolean isVisibles;
    private int blockAddress = 4;
    private int keyType = 0;
    private Handler mHandler = new Handler();
    private boolean isReadCard = false;
    public HardwareOpt mHardwareOpt;
    private String strKeyword="";
    private boolean isStoreCreatOrderEnter;

    public static SeachGuestFragment newInstance(boolean isStoreCreatOrderEnter, String param2) {
        SeachGuestFragment fragment = new SeachGuestFragment();
        Bundle args = new Bundle();
        args.putBoolean(ARG_PARAM1, isStoreCreatOrderEnter);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            isStoreCreatOrderEnter= getArguments().getBoolean(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_seach_guest, container, false);
        unbinder = ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    protected void initView() {
        tabOne.setChecked( SaveParams.isPassCard());
        tabTwo.setChecked( !SaveParams.isPassCard());
        mHardwareOpt = BaseApplication.mHardwareOpt;
        setStatusBarTintColor(R.color.normal_blue);
        KeyBoardUtil.showKeyboard(editText);
    }

    @Override
    protected void initListener() {
        super.initListener();
        editText.setOnEditorActionListener(mOnEditorActionListener);
   //     editText.addTextChangedListener(mTextWatcher);
    }

    @OnCheckedChanged({R.id.tab_one, R.id.tab_two})
    public void OnCheckedChanged(CompoundButton view, boolean checked) {
        if (checked) {
            switch (view.getId()) {
                case R.id.tab_one:
                    SaveParams.setIsPassCard(true);

                    break;
                case R.id.tab_two:
                    SaveParams.setIsPassCard(false);
                    break;

            }
        }
    }


    private TextWatcher mTextWatcher = new MyTextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);

            if (s.toString().trim().isEmpty()) {
                searchBtn.setEnabled(false);
                searchBtn.setAlpha(0.5f);
            } else {
                searchBtn.setEnabled(true);
                searchBtn.setAlpha(1);
            }

        }
    };


    private TextView.OnEditorActionListener mOnEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                    || actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) {

                queryKeyword(getText(editText));

            }

            return false;
        }


    };


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        dismissProgressDialog();
        mHandler.removeCallbacksAndMessages(null);
    }


    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(ReadCardEvent event) {

        if (!isVisibles) return;
        switch (event.getMessage()) {
            case READCARD:/*读卡*/
                HashMap mData = (HashMap) event.getData();
                String secretKey = (String) mData.get(ARG_PARAM1);
                String cardNumber = (String) mData.get(ARG_PARAM2);
                if (!CheckUtils.isEmpty(secretKey)){
                        rfidSecret = secretKey;
                        userInfoCard();
                }else  if (tabTwo.isChecked()){
                    if (CheckUtils.isEmpty(cardNumber)) {
                        T.show(getString(R.string.read_card_failure));
                        return;
                    } else {
                        Long intCardNumber = Long.parseLong(cardNumber,16);
                        L.i("intCardNumber="+intCardNumber);
                        queryKeyword(intCardNumber+"");
                    }

                }else{
                    T.show(getString(R.string.read_card_failure));
                }





                break;
            case NOSUPPORT:/*手机 不支持*/
                T.show("此手机不支持读卡");
                break;

        }
    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        isVisibles = true;
        isReadCard = true;
        postDelayedReadCard();
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        isReadCard = false;
        mHandler.removeCallbacksAndMessages(null);
    }


    @OnClick({R.id.back_btn, confirm_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case confirm_btn:
                isVisibles = false;
                isReadCard = false;

                start(BuildVipFragment.newInstance(strKeyword,isStoreCreatOrderEnter), SINGLETASK);
              //  queryKeyword(getText(editText));
                break;
        }
    }

    /**
     * 手机号搜索
     *
     * @param keyword
     */
    public void queryKeyword(final String keyword) {
        showProgressDialog();
        KeyBoardUtil.hideInputmethod(editText);
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("keyword", keyword);
        mHashMap.put("accessToken", SaveParams.getToken());
        L.i("mHashMap=" + mHashMap);
        addSubscription(apiStores().queryKeywordUse(Constant.createParameter(mHashMap)),
                new ApiCallback<SearchUserBean>() {
                    @Override
                    public void onSuccess(SearchUserBean model) {

                        if (model.getHttpCode() == 200) {
                            jumpFrament(model, keyword);

                        } else {

                            T.show(model.getMsg());

                        }

                    }


                    @Override
                    public void onFinish() {

                        dismissProgressDialog();

                    }
                });


    }

    private void jumpFrament(SearchUserBean model, final String keyword) {
        final SearchUserBean mSearchUserBean = model.getData();
        if (mSearchUserBean.getIsRegister() != 0) {  /*注册过得用户*/
            isVisibles = false;
            isReadCard = false;
            searchBtn.setVisibility(View.GONE);
            if (isStoreCreatOrderEnter){
                start(StoreClientInfoFragment.newInstance(mSearchUserBean,""), SINGLETASK);
            }else{
                start(GuestFragment.newInstance(mSearchUserBean,""), SINGLETASK);
            }


        } else {/*未注册*/
            T.show("未注冊，请创建该账户");
            strKeyword=keyword;
            searchBtn.setVisibility(View.VISIBLE);


        }
    }

    /**
     * 读卡
     */
    public void userInfoCard() {
        if (isReadCard) showProgressDialog();
        HashMap mHashMap = new HashMap<String, String>();
        L.i("rfidSecret=" + rfidSecret);
        mHashMap.put("rfidSecret", rfidSecret);
        mHashMap.put("accessToken", SaveParams.getToken());
        addSubscription(apiStores().userInfoCard(Constant.createParameter(mHashMap)),
                new ApiCallback<UserInfoCard>() {
                    @Override
                    public void onSuccess(UserInfoCard model) {

                        if (model.getHttpCode() == 200) {
                            UserInfoCard muserInfoCard = model.getData();
                            isVisibles = false;
                            isReadCard = false;
                            if (muserInfoCard.getIsBinding()) {
                                start(ClientFragment.newInstance(muserInfoCard,isStoreCreatOrderEnter), SINGLETASK);
                            } else { /*未绑定*/
                                start(SearchUserFragment.newInstance(muserInfoCard,isStoreCreatOrderEnter), SINGLETASK);
                            }

                        } else {

                            T.show(model.getMsg());
                        }

                    }


                    @Override
                    public void onFinish() {

                        dismissProgressDialog();

                    }
                });

    }


    /**
     * 读卡
     */
    private void postDelayedReadCard() {
        mHandler.removeCallbacksAndMessages(null);
        L.i("isReadCard=" + isReadCard);
        if (isReadCard && CheckUtils.isMIUIDevices()&&isAdded()) {
            mHandler.postDelayed(() -> swingCard(), 1000);
        }


    }


    /**
     * 刷卡
     */
    private void swingCard() {
        try {
            //支持M1卡
            int allType = AidlConstants.CardType.MIFARE;
            mHardwareOpt.checkCard(allType, mReadCardCallback, 60);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    ReadCardCallback mReadCardCallback = new ReadCardCallback.Stub() {
        @Override
        public void onCardDetected(final PayCardInfo cardInfo) throws RemoteException {
            if (isAdded()){
                mHandler.post(() -> m1auth());
            }

        }

        @Override
        public void onError(final int i, final String s) throws RemoteException {
            postDelayedReadCard();
        }

        @Override
        public void onStartCheckCard() throws RemoteException {
        }
    };

    /**
     * 授权
     */
    private void m1auth() {
        try {
            byte[] key = StringByteUtils.hexStringToBytes("31455433494F"); //密码
            int result = mHardwareOpt.mifareAuth(keyType, blockAddress, key);
            if (result == 0) {
                m1readblock();

            } else {
                T.show(getString(R.string.m1auth_1error));
                postDelayedReadCard();
            }
        } catch (Exception e) {
            e.printStackTrace();
            postDelayedReadCard();
            T.show(getString(R.string.m1auth_1error));

        }
    }

    /**
     * 读取块数据
     */
    private void m1readblock() {
        try {
            byte[] blockData = new byte[260];
            blockAddress = 4;
            int blockResult = mHardwareOpt.mifareReadBlock(blockAddress, blockData);
            if (blockResult == 0) {
                rfidSecret = StringByteUtils.convertHexToString(StringByteUtils.bytesToHexString(blockData));
                rfidSecret = rfidSecret.replace("�", "").replace("\u0090", "").trim();
                userInfoCard();

            } else {
                T.show(getString(R.string.m1readblock));
                postDelayedReadCard();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
            T.show(getString(R.string.m1readblock));
            postDelayedReadCard();
        }

    }

}
